package com.zq.springadmin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zq.springadmin.util.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/*
*
* 用户没有权限访问资源时，自定义返回信息
* */



@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Resource
    private ObjectMapper objectMapper;



    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

//        Map<String, Object> responseData = new HashMap<>();
//        responseData.put("status", HttpStatus.FORBIDDEN.value());
//        responseData.put("message", "Access Denied: You do not have permission to access this resource.");

        System.out.println("----------------------------------------");

        // 返回json格式的错误信息
        Result<String> responseData = new Result<>(403,"当前用户没有权限",null);

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(responseData));
    }
}
